
package io.lckgroup.modules.lck.resolver;

import io.lckgroup.modules.lck.annotation.AppLoginUser;
import io.lckgroup.modules.lck.entity.ShopMerchantInfoEntity;
import io.lckgroup.modules.lck.service.ShopMerchantInfoService;
import io.lckgroup.modules.lck.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@AppLoginUser，注入当前登录商户
 */
@Component
public class AppLoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ShopMerchantInfoService shopMerchantInfoService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(ShopMerchantInfoEntity.class) && parameter.hasParameterAnnotation(AppLoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }
        if (StringUtils.isBlank(token)) {
            return null;
        }

        //获取用户ID
        Claims claims = jwtUtils.getClaimByToken(token);
        Long userId = Long.parseLong(claims.getSubject());

        //获取用户信息
        ShopMerchantInfoEntity user = shopMerchantInfoService.getById(userId);

        return user;
    }
}
